package com.hyb.hybmodulesfront.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.SigninConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteSigninService;
import com.ruoyi.system.api.domain.Signin;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RabbitListener(queues = {"signQueue"})
public class SignInListener {

    @Autowired
    RemoteSigninService remoteSigninService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @RabbitHandler
    public void getMessage1(Signin signin, Channel channel, Message message)throws Exception{
        //防止重复消费
        try {
            String s = redisTemplate.opsForValue().get(SigninConstants.SIGN_IN_CONSUMER_KEY + signin.getActivityId() + ":" + signin.getUserId());
            if (StringUtils.isEmpty(s)){
                remoteSigninService.add(signin, SecurityConstants.INNER);
                redisTemplate.opsForValue().set(SigninConstants.SIGN_IN_CONSUMER_KEY+signin.getActivityId()+":"+signin.getUserId(),"1",10, TimeUnit.MINUTES);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }


    }

}
